package com.css.fxfzaqbz.modules.assess2.service.impl;

import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.repository.AttachmentInfoRepository;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.modules.assess1.service.DestoryAlgService;
import com.css.fxfzaqbz.modules.assess2.entity.Form;
import com.css.fxfzaqbz.modules.assess2.entity.UrgencysettleData;
import com.css.fxfzaqbz.modules.assess2.repository.UrgencysettleDataRepository;
import com.css.fxfzaqbz.modules.assess2.service.UrgencysettleDataService;
import com.css.fxfzaqbz.modules.assess2.vo.UrgencysettleVO;
import com.css.fxfzaqbz.modules.data.vo.AidedAnalyseVo;
import com.css.fxfzaqbz.modules.supergraph.vo.UrgencyVO;
import com.css.fxfzaqbz.util.*;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.entity.SUser;
import com.css.fxfzaqbz.zcpt.sys.service.SUserService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UrgencysettleDataServiceImpl implements UrgencysettleDataService {
    @Resource
    private UrgencysettleDataRepository urgencysettleDataRepository;
    @Resource
    private UrgencysettleDataService urgencysettleDataService;
    @Resource
    private SUserService sUserService;
    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;

    @Resource
    private AttachmentInfoService attachmentInfoService;

    @Value("${image.localDir}")
    private String localDir;

    @Resource
    private DestoryAlgService destoryAlgService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void judgeUrgencysettleData(UrgencysettleData urgencysettleData) {
        //根据活动id和任务类型查询数据库
        UrgencysettleData urgencysettleData1 = urgencysettleDataRepository.getUrgencysettleDataByContent(urgencysettleData.getUdContent(), urgencysettleData.getUdRelation());
        if (urgencysettleData1 == null) {
            urgencysettleDataService.saveUrgencysettleData(urgencysettleData);
        }
        if (urgencysettleData1 != null) {
            String userID = PlatformSessionContext.getUserID();
            Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
            urgencysettleDataRepository.deleteUrgencysettleData(urgencysettleData1.getUdId(), userID, currentTimestamp);
            urgencysettleDataService.saveUrgencysettleData(urgencysettleData);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUrgencysettleData(UrgencysettleData urgencysettleData) {
        urgencysettleData.setUdId(UUIDGenerator.getUUID());
        urgencysettleData.setDelFlag(YNEnum.N.toString());
        urgencysettleData.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        urgencysettleData.setCreateUser(PlatformSessionUtils.getUserId());
        urgencysettleData.setUdDate(PlatformDateUtils.getCurrentTimestamp());
        String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        if (sUser != null) {
            urgencysettleData.setUdPeople(sUser.getUserName());
        }
        urgencysettleData.setStatus(YNEnum.N.toString());
        urgencysettleDataRepository.saveUrgencysettleData(urgencysettleData);
    }

    @Override
    public List<Form> getExcel(String udFileId) throws Exception {
        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(udFileId);
        InputStream inputStream = null;
        String file = attach.getFileDirId() + attach.getAttachPath();
        File file1 = new File(file);
        if (file1.exists()) {
            inputStream = new BufferedInputStream(new FileInputStream(file1));
        }
        List<Form> forms = ExcelReaderUtil.readExcel2Bean(inputStream, Form.class,0);
        return forms;
    }

    @Override
    public HashMap<String, Object> getUrgencysettleDataById(String id) throws Exception {
        UrgencysettleData urgencysettleData = urgencysettleDataRepository.getUrgencysettleDataById(id);
        List<String> strings = new ArrayList<>();
        if (!PlatformObjectUtils.isEmpty(urgencysettleData.getUdDescription())) {
            String[] split = urgencysettleData.getUdDescription().split("&&");
            for (String s : split) {
                strings.add(s);
            }
            urgencysettleData.setDescriptions(strings);
        }
        String udFileId = urgencysettleData.getUdFileId();
        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(udFileId);
        List<Form> forms = getExcel(udFileId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("attach", attach);
        map.put("urgencysettleData", urgencysettleData);
        map.put("forms", forms);
        return map;
    }

    @Override
    public void deleteUrgencysettleData(String id) {
        String userID = PlatformSessionContext.getUserID();
        Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
        urgencysettleDataRepository.deleteUrgencysettleData(id, userID, currentTimestamp);
    }

    @Override
    public UrgencysettleData updateUrgencysettleData(UrgencysettleData urgencysettleData) {
        urgencysettleData.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        urgencysettleData.setUpdateUser(PlatformSessionUtils.getUserId());
        return urgencysettleDataRepository.updateUrgencysettleData(urgencysettleData);
    }

    @Override
    public List<UrgencysettleData> getUrgencysettleDataByIaId(String id) {
        return urgencysettleDataRepository.getUrgencysettleDataByIaId(id);
    }

    @Override
    public List<UrgencysettleData> getUrgencysettleDataByActiveId(String id) {
        List<UrgencysettleData> urgencysettleDataByActiveId = urgencysettleDataRepository.getUrgencysettleDataByActiveId(id);
        for (UrgencysettleData urgencysettleData : urgencysettleDataByActiveId) {
            List<String> strings = new ArrayList<>();
            if (!PlatformObjectUtils.isEmpty(urgencysettleData.getUdDescription())) {
                String[] split = urgencysettleData.getUdDescription().split("&&");
                for (String s : split) {
                    strings.add(s);
                }
                urgencysettleData.setDescriptions(strings);
            }
        }
        return urgencysettleDataByActiveId;
    }

    @Override
    public boolean check(UrgencysettleData urgencysettleData) {
        List<UrgencysettleData> urgencysettleDatas = urgencysettleDataRepository.check(urgencysettleData);
        if (urgencysettleDatas == null || urgencysettleDatas.size() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public void submitResult(String id) {
        UrgencysettleData urgencysettleData = urgencysettleDataRepository.getUrgencysettleDataById(id);
        List<UrgencysettleData> urgencysettleDatas = urgencysettleDataRepository.getByEntity(urgencysettleData);
        String description = "";
        if (urgencysettleDatas != null && urgencysettleDatas.size() > 0) {
            description = urgencysettleDatas.get(0).getUdDescription();
        }
        urgencysettleDataRepository.submitResult(id, description);
    }

    @Override
    public void saveDescription(AidedAnalyseVo aidedAnalyseVo) {
        List<String> descriptions = aidedAnalyseVo.getDescriptions();
        String description = StringUtils.join(descriptions, "&&");
        urgencysettleDataRepository.saveDescription(aidedAnalyseVo.getIds(), description);

    }

    @Override
    public void removeResult(String id) {
        String description = "";
        urgencysettleDataRepository.removeResult(id, description);
    }

    @Override
    public void finalSubmission(List<String> ids) {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String userName = sUser.getUserName();
        String mobilePhone = sUser.getMobilePhone();
        Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
        urgencysettleDataRepository.finalSubmission(ids, userName, mobilePhone,currentTimestamp);
    }

    @Override
    public List<UrgencysettleData> getUrgencysettleDataByIaIdAndType(String iaId, String xjjaz) {
        return urgencysettleDataRepository.getUrgencysettleDataByIaIdAndType(iaId,xjjaz);
    }

    @Override
    public UrgencysettleData getUrgencyByIaId(String iaId) {
        return urgencysettleDataRepository.getUrgencyByIaId(iaId);
    }

    @Override
    public int isCheck(UrgencysettleData urgencysettleData) {
        int a = urgencysettleDataRepository.getNumber(urgencysettleData);
        if (a==0){
            return 0;
        }else {
            return 1;
        }

    }

    @Override
    public void saveUrgencysettleDataByPG(UrgencysettleVO urgencysettleVO){
//        List<AlgEntity> list = destoryAlgService.getAlgByIaId(urgencysettleVO.getIaId());
        List<UrgencyVO> list = urgencysettleVO.getList();
        //将数据写入到Excel 中
        //创建Excel文件薄
        HSSFWorkbook workbook=new HSSFWorkbook();
        //创建工作表sheeet
        HSSFSheet sheet=workbook.createSheet();
        HSSFRow row=sheet.createRow(0);
        HSSFCell cell_title = null;
        cell_title=row.createCell(0);
        cell_title.setCellValue("省");
        cell_title=row.createCell(1);
        cell_title.setCellValue("市");
        cell_title=row.createCell(2);
        cell_title.setCellValue("区(县)");
        cell_title=row.createCell(3);
        cell_title.setCellValue("预估所需紧急安置人数(人)");
        for (int i = 0; i < list.size(); i++) {
                HSSFRow row1=sheet.createRow(i+1);
                HSSFCell cell_title1 = null;
                cell_title1=row1.createCell(0);
                cell_title1.setCellValue(list.get(i).getProvince());
                cell_title1=row1.createCell(1);
                cell_title1.setCellValue(list.get(i).getCity());
                cell_title1=row1.createCell(2);
                cell_title1.setCellValue(list.get(i).getPrefecture());
                cell_title1=row1.createCell(3);
                cell_title1.setCellValue(list.get(i).getResettleXz());
//                if (list.get(i).getResettleXz()!=null){
//                    cell_title1.setCellValue(list.get(i).getResettleXz());
//                }else {
//                    cell_title1.setCellValue(list.get(i).getResettle());
//                }



        }

            String fileId="";
            //创建一个文件
            try {
                String savePath=localDir;
                File file=new File(savePath,"需紧急安置人员模板"+".xlsx");
                if (!new File(savePath).exists()) {
                    new File(savePath).mkdirs();
                }
                file.createNewFile();
                FileOutputStream stream= FileUtils.openOutputStream(file);
                workbook.write(stream);
                stream.close();
                MultipartFile cMultiFile = getMultipartFile(file);
                fileId= getImageFileId(cMultiFile);

                File file1 = new File(savePath);
                File[] files = file1.listFiles();
                for (File file11 : files) {
                    if (file11.isFile()){
                        file11.delete();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            UrgencysettleData urgencysettleData=new UrgencysettleData();
            urgencysettleData.setUdRelation(urgencysettleVO.getIaId());
            urgencysettleData.setUdTitle(urgencysettleVO.getUdTitle());
            urgencysettleData.setDataMessage(urgencysettleVO.getDataMessage());
            urgencysettleData.setUdContent("需紧急安置人员");
            urgencysettleData.setUdFileId(fileId);
            int a = urgencysettleDataRepository.getNumber(urgencysettleData);
            if (a!=0) {
                Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
                String userIDd = PlatformSessionContext.getUserID();
                urgencysettleDataRepository.deleteTJ(urgencysettleData.getUdRelation(),currentTimestamp,userIDd);
            }
            urgencysettleData.setUdId(UUIDGenerator.getUUID());
            urgencysettleData.setDelFlag(YNEnum.N.toString());
            urgencysettleData.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            urgencysettleData.setCreateUser(PlatformSessionUtils.getUserId());
            urgencysettleData.setUdDate(PlatformDateUtils.getCurrentTimestamp());
            String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            if (sUser != null) {
                urgencysettleData.setUdPeople(sUser.getUserName());
            }
            urgencysettleData.setStatus(YNEnum.N.toString());
            urgencysettleDataRepository.saveUrgencysettleData(urgencysettleData);
    }

    @Override
    public Boolean getNum(String iaId) {
        return urgencysettleDataRepository.getNum(iaId);
    }

    @Override
    public void cover(String iaId,String id) {
        Boolean a = urgencysettleDataRepository.getNum(iaId);
        if (a) {
            Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
            String userIDd = PlatformSessionContext.getUserID();
            urgencysettleDataRepository.deleteTJ(iaId,currentTimestamp,userIDd);
        }
        this.submitResult(id);
    }

    private MultipartFile getMultipartFile(File file){
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(),file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }


    private String getImageFileId(MultipartFile image)throws IOException {
        //获取文件名称
        String fileName=image.getOriginalFilename();
        //获取文件上传的本地路径
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
        String savePath = localDir + dateDir;
        //构建文件
        assert fileName != null;
        //上传文件
        String realFileName = uploadFile(fileName,savePath,image);
        //构建实体类
        AttachmentInfoEntity attachmentInfoEntity = buildAttachment(fileName,dateDir,realFileName);
        List<AttachmentInfoEntity> list=new ArrayList<>();
        list.add(attachmentInfoEntity);
        attachmentInfoService.save(list);
        return attachmentInfoEntity.getAttachId();
    }

    private AttachmentInfoEntity buildAttachment(String fileName, String dateDir, String realFileName) {
        AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
        attachmentInfoEntity.setAttachId(com.css.fxfzaqbz.util.StringUtils.buildPrimaryId());
        attachmentInfoEntity.setAttachName(fileName);
        attachmentInfoEntity.setAttachPath(dateDir + "/" + realFileName);
        attachmentInfoEntity.setFileDirId(localDir);
        attachmentInfoEntity.setIsValid("1");
        attachmentInfoEntity.setIsCompleted("1");
        return attachmentInfoEntity;
    }

    private String uploadFile(String fileName, String savePath, MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
        // .jpg  .pdf  .txt  .docs
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 拼文件名  真实的文件名称
        String realFileName = preFileName + "_" + System.currentTimeMillis() + fileType;
        //判断文件夹是否存在如果不存在则创建
        if (!new File(savePath).exists()) {
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, realFileName);
        multipartFile.transferTo(file);
        return realFileName;
    }

}
